package com.test.controller;

import com.test.pojo.Users;
import com.test.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private IUsersService usersService;

    public IUsersService getUsersService() {
        return usersService;
    }

    public void setUsersService(IUsersService usersService) {
        this.usersService = usersService;
    }

    @RequestMapping("/regUi")
    public String regUi()
    {
        return "register";
    }

    @RequestMapping("/reg")
    public String reg(Users user)
    {
        //存入数据库
         int i=usersService.reg(user);
         if(i>0)
             return "login";
         else
             return "error";

    }

    @RequestMapping("/isExistsUname")
    @ResponseBody
    public String isExistsUname(String uname)
    {
            int i=  usersService.isExistsUname(uname);

            return i+"";

    }

    //进入登录界面
    @RequestMapping("/loginUi")
    public String loginUi()
    {
         return "login";
    }

    @RequestMapping("/checkLogin")
    public String checkLogin(Users user, HttpServletRequest request)
    {
         //判断用户名和密码是否正确
        Users loginUser=  usersService.login(user);

        //如果登录成功
        if(loginUser!=null)
        {
           HttpSession session= request.getSession();

           session.setAttribute("loginUser",loginUser);

           return "redirect:/index/index";
        }
        else
        {
            return "loginError";
        }

    }

    //退出登录
    @RequestMapping("/logOut")
    public String logOut(HttpServletRequest request)
    {
         //销毁session
         HttpSession session=request.getSession();

         session.invalidate();

         //回到首页
         return "redirect:/index/index";

    }


}
